// 我的分析页面
import React, { CSSProperties, RefObject } from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps } from 'react-router';
import { Row, Col, Input, message, Popconfirm, Button, Table, Tabs } from 'antd';
import { SearchOutlined, PlusCircleOutlined, DeleteOutlined, BarChartOutlined } from '@ant-design/icons';

import styles from './index.module.scss';
import { getCategoryTree, getChartComponent, delChartComponent, delAnalyseCategory } from 'src/services/AnalyseManage';
import { withRouter } from 'react-router-dom';
import TreeNode from 'src/pages/AnalyseManage/PredefinedReport/components/TreeNode';
import BdhButton from 'src/pages/Components/BdhButton';
import Charts from './components/Charts';
import CreateFolder from './components/CreateFolder';
import AddModal from './components/AddModal';
import OperateComponent from './components/OperateComponent';
import NewReportModal from 'src/pages/AnalyseManage/Components/NewReportModal';
import RenameItem from './components/RenameItem';
import ViewChart from './components/ViewChart';
import { debounce } from 'src/libs/utils';
import { SCROLL_POSITION } from '../EditReport/topics';
import PubSub from 'pubsub-js';
import { encryptParam } from 'src/libs/paramsEncrypt';

interface listItemType {
	name: string;
	id: string;
	effect: string;
	isFile: boolean;
}

interface RProps {
	btnAuth: any;
	match: {
		params: {
			id: string;
			isEdit: string;
		};
	};
}
class GraphicIndicatorLibrary extends React.Component<RouteComponentProps & RProps> {
	state = {
		// table相关数据
		data: [],
		fileData: {},
		tableLoading: false,
		selectedRowKeys: [],
		selectedRows: [],

		// 当前选中的树节点
		activeTreeNode: '',
		treeData: [],
		chartConfigs: [],

		// 新建文件夹模态框
		createFolderVisible: false,
		isUpdateFolder: false,
		updateFolderData: {},

		// 新建仪表板
		addDashbord: false,

		// 添加至仪表板模态框
		addModalVisable: false,

		// 重命名相关数据
		renameVisable: false,
		detailData: {},

		// 查看详细信息
		viewVisable: false,

		// 当前的 需要添加至仪表盘的 config
		currentConfigs: [],

		tabValue: 'chart', // chart

		page: 1,
		pageSize: 10,
		total: 0,
	};

	//	列表表头配置
	columns = [
		{
			title: '报表名称',
			dataIndex: 'name',
			render: ( text, record ) => {
				let icon;
				const paddingLeft = record.isFile ? 0 : '24px';
				if ( record.isFile ) {
					icon = <span className={'iconfont bdhwenjianjiadakai'} style={{ marginRight: '10px' }}></span>;
				} else {
					icon = <BarChartOutlined className={styles.green_btn} style={{ marginRight: '10px' }} />;
				}
				return (
					<div style={{ paddingLeft }}>
						{
							record.isFile ? ( <>{icon}{record.name}</> ) : (
								<span className="bdh-link" onClick={() => this.handleView( true, record )}>
									{icon}{record.name}
								</span>
							)
						}
					</div>
				);
			},
		},
		{
			title: '描述',
			dataIndex: 'describe',
		},
		{
			title: '操作',
			key: 'action',
			// eslint-disable-next-line react/display-name
			render: ( record: listItemType ) => (
				<OperateComponent
					record={record}
					handleDelete={( item ) => this.handleDelete( [ item.componentId ], item.parentId )}
					addDashbord={( config ) => {
						this.handleAddToPanel( true, [ config.content ] );
					}}
					handleView={( item ) => this.handleView( true, item )}
					handleEditFolder={( item ) => this.handleEditFolder( true, item )}
					handleDeleteFolder={this.handleDeleteFolder}
					handleRename={( item ) => this.handleRename( true, item )}
					btnAuth={ this.props.btnAuth }
				></OperateComponent>
			),
		},
	];

	modalRef: RefObject<any> = React.createRef();

	componentDidMount() {
		this.loadChartsDatas();
		document.getElementById( 'table_container' ).addEventListener( 'scroll',debounce( this.publishScrollInfo, 500 ) );
	}

	publishScrollInfo = ( event ) => {
		console.log( 'scroll' );
		PubSub.publish( SCROLL_POSITION, { bottom: event.target.getBoundingClientRect().bottom } );
	};

	loadChartsDatas = async () => {
		let response: any = {};
		// 我的分析
		response = await getCategoryTree( { type: 'COMPONENT' } );
		if ( response.data && response.data.success ) {
			if ( response.data.data.length > 0 ) {
				const fileData = { ...response.data.data[0], isFile: true };
				this.setState(
					{
						treeData: response.data.data || [],
						fileData,
					},
					() => {
						this.clickNode( fileData );
					}
				);
			}
		}
	};

	clickNode = ( item ) => {
		this.setState(
			{
				activeTreeNode: item.id,
				fileData: item,
				tableLoading: true,
			},
			() => {
				this.getList();
			}
		);
	};

	// 请求所有图形数据
	getList = async () => {
		const params = {
			parentId: this.state.activeTreeNode,
			page: this.state.page,
			size: this.state.tabValue === 'table' ? this.state.pageSize : 99999,
		};
		let response = await getChartComponent( params );
		if ( response.data && response.data.success ) {
			let initData = [],
				fieldName = '',
				row = response.data.data.rows || [];
			if ( this.state.tabValue === 'table' ) {
				fieldName = 'data';
				initData = this.state.page === 1 ? [ this.state.fileData, ...row ] : row;
			} else {
				fieldName = 'chartConfigs';
				initData = row;
			}

			const data = initData.map( ( item, index ) => {
				return {
					...item,
					content: item.content ? JSON.parse( item.content ) : '',
					key: index,
				};
			} );
			this.setState( { [fieldName]: data, tableLoading: false, total: response.data.data.total || 0 } );
		}
	};

	handleJump = async ( id ) => {
		this.props.history.push( { pathname: `/analyseManage/editReport/${encryptParam( id )}/${encryptParam( 'true' )}/${encryptParam( 'EDIT' )}` } );
	};

	newFolderVisible = ( value ) => {
		this.setState( {
			createFolderVisible: value,
			isUpdateFolder: false,
			updateFolderData: {},
		} );
	};

	// 添加至仪表板
	handleAddToPanel = ( visible, configs ) => {
		this.setState( { addModalVisable: visible, currentConfigs: configs } );
	};

	handleSelectionChange = ( selectedRowKeys, selectedRows ) => {
		this.setState( { selectedRowKeys, selectedRows } );
	};

	handleView = ( visiable, item? ) => {
		console.log( visiable, item );
		this.setState( { viewVisable: visiable, detailData: item } );
	};

	// 删除文件夹
	handleDeleteFolder = async ( item: listItemType ) => {
		const response = await delAnalyseCategory( item.id );
		if ( response.data && response.data.success ) {
			this.loadChartsDatas();
			message.success( '操作成功' );
		}
	};

	// 修改/新建 文件夹
	handleEditFolder = ( t, item? ) => {
		let updateFolderData = {};
		if ( t ) {
			updateFolderData = Object.assign( {}, item );
		}

		this.setState( { isUpdateFolder: t, updateFolderData, createFolderVisible: true }, () => {
			if ( t ) {
				setTimeout( () => {
					if ( t ) {
						this.modalRef.current.setFieldsValue( {
							name: item.name,
							des: item.des,
						} );
					}
				}, 100 );
			}
		} );
	};

	handleRename = ( t, item? ) => {
		this.setState( { renameVisable: t, detailData: { ...item } }, () => {
			if ( t ) {
				setTimeout( () => {
					if ( t ) {
						this.modalRef.current.setFieldsValue( {
							name: item.name,
							describe: item.describe,
						} );
					}
				}, 100 );
			}
		} );
	};

	//	批量删除
	handleBatchDel = async () => {
		const componentIds = this.state.selectedRows.map( ( v ) => {
			return v.componentId;
		} );

		this.handleDelete( componentIds, this.state.selectedRows[0].parentId );
	};

	// 删除图表
	handleDelete = async ( componentIds: Array<string>, parentId: string ) => {
		let response = await delChartComponent( { componentIds: componentIds, parentId: parentId } );
		if ( response.data && response.data.success ) {
			message.success( '删除成功' );
			this.getList();
		}
	};

	// 批量添加至仪表板
	handleBacthAddToPanel = async () => {
		const configs = this.state.selectedRows.map( ( v ) => {
			return v.content;
		} );

		this.handleAddToPanel( true, configs );
	};

	// 搜索框搜索
	handleSearchInput = ( e ) => {
		// e.persist();
		// let value = e.target.value;
		// this.setState( {
		// 	keyword: value,
		// } );
		// if ( this.state.timer ) clearTimeout( this.state.timer );
		// let timer = setTimeout( () => {
		// 	this.getList();
		// }, 300 );
		// this.setState( {
		// 	timer: timer,
		// } );
	};

	handleTabChange = ( key ) => {
		this.setState( { tabValue: key, page: 1 }, () => {
			this.getList();
		} );
	};

	//	切换页码
	handlePageChange = ( pageNumber: number ) => {
		this.setState(
			{
				page: pageNumber,
			},
			() => {
				this.getList();
			}
		);
	};

	//	修改每页数量
	setPageSize = ( size: number ) => {
		this.setState( {
			pageSize: size,
		} );
	};

	render() {
		const btnAuth = this.props.btnAuth;
		return (
			<>
				<div className={styles.report_contanier}>
					<div className={styles.tree_container}>
						<p>图形指标库</p>
						<div>
							{this.state.treeData.map( ( item, index: number ) => (
								<TreeNode
									activeNodeId={this.state.activeTreeNode}
									key={index}
									id={item.id}
									label={item.name}
									handleClick={() => this.clickNode( { ...item, isFile: true } )}
								></TreeNode>
							) )}
						</div>
					</div>
					<div className={styles.table_container}>
						<Row justify="space-between">
							<Col span={12} style={{ textAlign: 'left' }}>
								{
									btnAuth.includes( 'bi_graphLib_addFolder' ) && (
										<BdhButton
											align="horizontal"
											label="新建文件夹"
											className="gery-transpanent"
											onClick={() => this.handleEditFolder( false )}
										></BdhButton>
									)
								}
								{this.state.tabValue === 'table' && (
									<>
										{
											btnAuth.includes( 'bi_graphLib_batchDel' ) && (
												<Popconfirm
													okText="确定"
													cancelText="取消"
													title="确定删除选中数据？"
													placement="bottom"
													onConfirm={this.handleBatchDel}
												>
													<BdhButton
														align="horizontal"
														label="批量删除"
														className="grey-transpanent"
														onClick={null}
														icon={<DeleteOutlined />}
													></BdhButton>
												</Popconfirm>
											)
										}
										{
											btnAuth.includes( 'bi_graphLib_batchToDash' ) && (
												<Button type="primary" icon={<PlusCircleOutlined />} onClick={this.handleBacthAddToPanel}>
													批量添加至仪表板
												</Button>
											)
										}
									</>
								)}
							</Col>
							<Col xs={24} sm={6} md={6} lg={6} xl={6} style={{ textAlign: 'right' }}>
								<Input placeholder="请输入名称回车搜索" allowClear onChange={this.handleSearchInput} prefix={<SearchOutlined />} />
							</Col>
						</Row>
						<div className={styles.table_wrapper}>
							<Tabs defaultActiveKey="chart" onChange={this.handleTabChange}>
								<Tabs.TabPane tab="图形" key="chart">
									<div id='table_container' style={{ overflow: 'auto',height: '500px' } as CSSProperties}>
										{this.state.tabValue === 'chart' && this.state.chartConfigs && 
										this.state.chartConfigs.length ? (
												<Charts
													chartsList={this.state.chartConfigs}
													handleAddToPanel={( visible, configs ) => this.handleAddToPanel( visible, configs )}
													handleDelete={( item ) => this.handleDelete( [ item.componentId ], item.parentId )}
												></Charts>
											
											) : (
												<>
													<p style={{ textAlign: 'center', lineHeight: '30px' }}>无数据</p>
												</>
											)}
									</div>
								</Tabs.TabPane>
								<Tabs.TabPane tab="列表" key="table">
									{this.state.tabValue === 'table' && <Table
										loading={this.state.tableLoading}
										childrenColumnName="null"
										scroll={{ x: '100%' }}
										tableLayout="fixed"
										columns={this.columns}
										dataSource={this.state.data}
										className={styles.table}
										bordered={true}
										rowKey={( row: listItemType ) => row.id}
										size="middle"
										rowSelection={{ type: 'checkbox', onChange: this.handleSelectionChange }}
										rowClassName={ ( row ) => row.isFile ? 'row-folder' : '' }
										pagination={{
											showSizeChanger: true,
											pageSize: this.state.pageSize,
											total: this.state.total,
											onChange: this.handlePageChange,
											onShowSizeChange: ( current, size ) => this.setPageSize( size ),
											showTotal: ( total ) => `共 ${total} 条`,
										}}
									/>}
								</Tabs.TabPane>
							</Tabs>
						</div>
					</div>
				</div>

				{/* 新增文件夹弹窗 */}
				<CreateFolder
					ref={this.modalRef}
					modalVisible={this.state.createFolderVisible}
					onSuccess={() => this.loadChartsDatas()}
					isUpdate={this.state.isUpdateFolder}
					updateFolderData={this.state.updateFolderData}
					handleCancel={() => this.newFolderVisible( false )}
				></CreateFolder>

				{/* 添加至仪表板 */}
				<AddModal
					modalVisible={this.state.addModalVisable}
					currentConfigs={this.state.currentConfigs}
					cancelHandle={() => this.handleAddToPanel( false, [] )}
					handleJump={( id ) => this.handleJump( id )}
					okHandle={() => this.handleAddToPanel( false, [] )}
				></AddModal>

				{/* 新建仪表板 */}
				<NewReportModal
					modalVisible={this.state.addDashbord}
					name="仪表板"
					pageType="dashboard"
					onSuccess={() => {}}
					onCancel={() => this.setState( { addDashbord: false } )}
				></NewReportModal>

				{/* 重命名 */}
				<RenameItem
					ref={this.modalRef}
					modalVisible={this.state.renameVisable}
					updateData={this.state.detailData}
					handleCancel={() => this.handleRename( false, {} )}
					onSuccess={() => this.getList()}
				></RenameItem>

				{/* 查看图形 */}
				{this.state.viewVisable && (
					<ViewChart
						data={this.state.detailData}
						modalVisible={this.state.viewVisable}
						handleCancel={() => this.handleView( false, {} )}
					></ViewChart>
				)}
			</>
		);
	}
}

//	映射state到当前组件
const mapStateToProps = ( state ) => {
	return {
		btnAuth: state.btnAuth,
	};
};

export default withRouter( connect( mapStateToProps )( GraphicIndicatorLibrary ) );
